<?php
namespace Home\Controller;
use Think\Controller;

class IdentifyController extends Controller
{	
	/**
	 * 个人中心
	 * 网页授权
	 * */

	public function identify(){
//	    dump($_GET);
//	    die;
		//dump($_GET);die;
//	    dump($_SERVER['HTTP_HOST']);die;
		//通过当前域名获取对应的平台的appid
		$domain = $_SERVER['HTTP_HOST'];//绑定域名
		$map['domain'] = $domain;
		$platform = D('platform')->field('appid')->where($map)->find();
//		die( D('platform')->getLastSql() );
echo  D('platform')->getLastSql();
echo "<br/>";
//print_r($platform);
//die();
		$controller = '';
		if(!empty($_GET['redirect'])) {
//		    echo "kengjie";die();
			$controller =  $_GET['redirect'];
			$controller = str_replace('&','/',$controller);
			$controller = str_replace('=','/',$controller);
//			echo $controller;die();
			if(!empty(strpos($_GET["redirect"],"recharge")))
				$controller = substr($_GET['redirect'],0,strpos($_GET['redirect'],'recharge')+strlen('recharge'));
		}
//		echo $controller;die;
		//
		//dump($controller);die;

        //跳转认证
		$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$platform['appid'].'&redirect_uri=http://'.$domain.'/Home/Identify/identify_is_ok/&response_type=code&scope=snsapi_userinfo&state='.$controller.'#wechat_redirect';
//		die();
//		die( $url );
		header("Location: $url");
	}
	
	/**
	 * 再次验证获取用户信息
	 * 最后跳转用户信息页面
	 */
    public function identify_is_ok(){
        if(empty($_REQUEST['code']) || empty($_REQUEST['state'])) {
            echo 'bad link';
            die;
        }

		//获取平台的相关信息
        $domain = $_SERVER['HTTP_HOST'];
        $map['domain'] = $domain;
        $platform = D('platform')->where($map)->find();
//        print_r( $platform);die();
		
		//获取平台数据库token
		if(intval($platform['out_time']) > time())	{
			$token = getWeChatToken($platform['appid'],$platform['secret'],$platform['token']);
		}
		else{

			$token = getWeChatToken($platform['appid'],$platform['secret']);
		}		

		//获取网页授权的token
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$platform['appid'].'&secret='.$platform['secret'].'&code='.$_REQUEST['code'].'&grant_type=authorization_code';
        $info = weChatCurl($url);


//        print_r( $info );die();

        if(!empty($info['errcode'])){
            header('Location: http://'.$_SERVER['HTTP_HOST'].'/Home/Identify/identify?redirect='.$_REQUEST['state']);
            die;
        }
		
		//判断用户是否关注平台
        $user_info = weChatCurl('https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$token.'&openid='.$info['openid'].'&lang=zh_CN');
		//dump($user_info);die;
        $user['nickname'] = $user_info['nickname'];
        $user['img'] = $user_info['headimgurl'];
        $user['open_id'] = $user_info['openid'];
        $user['sex'] = $user_info['sex'];
        $user['domain'] = $_SERVER['HTTP_HOST'];
		$user['open_id_pre'] = substr($info['openid'], 0, 6);
        $user['addtime'] = date('Y-m-d H:i:s');//注册时间
        $user['subscribe'] = $user_info['subscribe'] ? $user_info['subscribe'] : 0; //是否关注
//        print_r($user);die();
        //如果用户未关注的情况下就使用其他接口把nickname,img等其他信息拿到
        if($user['subscribe'] == 0){
            $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$info["access_token"]."&openid=".$info["openid"]."&lang=zh_CN";
            $user_s = weChatCurl($url);
            $user['nickname'] = $user_s['nickname'];
            $user['img'] = $user_s['headimgurl'];
            $user['open_id'] = $user_s['openid'];
            $user['sex'] = $user_s['sex'];
            $user['domain'] = $_SERVER['HTTP_HOST'];
            $user['addtime'] = date('Y-m-d H:i:s');//注册时间
            //dump($user_s);die;
        }


		
		//判断是否是代理商推荐过来的用户
		if(!empty($_REQUEST['state'])) {
			$uid_begin = strpos($_REQUEST['state'], 'uid/');
			$uid_start = strpos($_REQUEST['state'], 'uid/') + strlen('uid/');
			if(!empty($uid_begin)) {
				$uid = substr($_REQUEST['state'], $uid_start, strlen($_REQUEST['state']) - $uid_start);
				$user['proxy_id'] = $uid;
			}
		}
		
		//老用户推荐新用户判断
        if(!empty($_REQUEST['state'])) {
            //echo $_GET['redirect'];die;
            $uid_begin = strpos($_REQUEST['state'], 'old_openid/');
            $uid_start = strpos($_REQUEST['state'], 'old_openid/') + strlen('old_openid/');
            if(!empty($uid_begin)) {
                $proxy_open_id = substr($_REQUEST['state'], $uid_start, strlen($_REQUEST['state']) - $uid_start);
                $user['proxy_open_id'] = $proxy_open_id;
            }
        }		
		
		//判断用户是否存在与数据表
        $open_id = $user_info['openid'];
        //dump($open_id);die;
		$user_rs = D('user')->where("open_id='$open_id'")->select();
		//dump($user_rs);die;
		//如果不存在就添加用户

		if(empty($user_rs)){
//		    print_r($user);
			D('user')->add($user);
//			echo "<br/>";
//			echo D('user')->getLastSql();
//			die();
		}else{
		  $session_data['phone'] = $user_rs[0]['phone'];
		}
		//echo 222;die;

		//添加负载均衡的session登录信息
		$session_data['nickname'] = $user['nickname'];
		$session_data['img'] = $user['img'];
		$session_data['open_id'] = $user['open_id'];
		$session_data['open_id_pre'] = $user['open_id_pre'];
		$session_data['sex'] = $user['sex'];
		$session_data['domain'] = $user['domain'];
		$session_data['addtime'] = time() + 3600 * 12;
		$session_data['session_id'] = session_id();

		D('session')->add($session_data);
		
		//直接跳转
        //获得落地域名,且域名没有被腾讯杀掉
        $d_map['set_domain'] = $_SERVER['HTTP_HOST'];
        $d_map['status'] = 0;
        $d_info = D('domain')->field('show_domain')->where($d_map)->find();
//        echo D('domain')->getLastSql();
//        echo "<br/>";
//        print_r( $_REQUEST );
//        die();


        $url = 'http://'.$d_info['show_domain'].$_REQUEST['state'].'?open_id_pre='.$session_data['open_id_pre'].'&session_id='.session_id();
//        echo $url;die;
        header("Location: $url");
    }
}
